package com.ruoyi.web.controller.lh;

import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.lh.domain.Machine;
import com.ruoyi.lh.domain.Project;
import com.ruoyi.lh.domain.User;
import com.ruoyi.lh.service.IMachineService;
import com.ruoyi.lh.service.IProjectService;
import com.ruoyi.lh.service.IUserService;
import com.ruoyi.web.controller.common.CommonController;
import com.ruoyi.web.controller.tool.CreateHeaderFooter;
import com.ruoyi.web.controller.tool.DeduplicationUtil;
import com.ruoyi.web.controller.tool.PdfUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.lh.domain.Software;
import com.ruoyi.lh.service.ISoftwareService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 软件Controller
 *
 * @author LH
 * @date 2023-08-02
 */
@Controller
@RequestMapping("/lh/software")
public class SoftwareController extends BaseController {
  private String prefix = "lh/software";

  @Autowired private ISoftwareService softwareService;

  @Autowired private IProjectService projectService;

  private static final Logger log = LoggerFactory.getLogger(SoftwareController.class);

  @Autowired
  private IUserService userService;

  @RequiresPermissions("lh:software:view")
  @GetMapping()
  public String software(Model model) {
    List<Software> softwareList = softwareService.selectSoftwareList(new Software());
    model.addAttribute(
        "softwareVersionList",
        softwareList.stream()
            .filter(DeduplicationUtil.distinctByKey(Software::getSoftwareVersion))
            .collect(Collectors.toList()));
    List<User> users = userService.selectUserList(new User());
    User u;
    if(null == users || users.isEmpty()) {
      u = new User();
    } else {
      u = users.get(0);
    }
    model.addAttribute("settings", u);
    return prefix + "/software";
  }

  @RequiresPermissions("lh:software:download")
  @GetMapping("downloadResult")
  public String downloadResult(Model model) {
    List<Software> softwareList = softwareService.selectSoftwareList(new Software());
    model.addAttribute(
        "softwareNameList",
        softwareList.stream()
            .filter(DeduplicationUtil.distinctByKey(Software::getSoftwareName))
            .collect(Collectors.toList()));
    model.addAttribute(
        "softwareVersionList",
        softwareList.stream()
            .filter(DeduplicationUtil.distinctByKey(Software::getSoftwareVersion))
            .collect(Collectors.toList()));
    return prefix + "/download";
  }

  @RequiresPermissions("lh:software:software")
  @GetMapping("softwareDownload")
  public String softwareDownload(Model model) {
    List<Software> softwareList = softwareService.selectSoftwareList(new Software());
    model.addAttribute(
        "softwareNameList",
        softwareList.stream()
            .filter(DeduplicationUtil.distinctByKey(Software::getSoftwareName))
            .collect(Collectors.toList()));
    model.addAttribute(
        "softwareVersionList",
        softwareList.stream()
            .filter(DeduplicationUtil.distinctByKey(Software::getSoftwareVersion))
            .collect(Collectors.toList()));
    return prefix + "/softwareDownload";
  }

  /** 查询软件列表 */
  @RequiresPermissions("lh:software:list")
  @PostMapping("/list")
  @ResponseBody
  public TableDataInfo list(Software software) {
    startPage();
    List<Software> list = softwareService.selectSoftwareList(software);
    return getDataTable(list);
  }

  /** 导出软件列表 */
  @RequiresPermissions("lh:software:export")
  @Log(title = "软件", businessType = BusinessType.EXPORT)
  @PostMapping("/export")
  @ResponseBody
  public AjaxResult export(Software software) {
    List<Software> list = softwareService.selectSoftwareList(software);
    ExcelUtil<Software> util = new ExcelUtil<Software>(Software.class);
    return util.exportExcel(list, "软件数据");
  }

  /** 新增软件 */
  @GetMapping("/add")
  public String add(Model model) {
    List<Project> list = projectService.selectProjectList(new Project());
    model.addAttribute("projectList", list);
    return prefix + "/add";
  }

  /** 新增保存软件 */
  @RequiresPermissions("lh:software:add")
  @Log(title = "软件", businessType = BusinessType.INSERT)
  @PostMapping("/add")
  @ResponseBody
  public AjaxResult addSave(Software software) {
    List<User> users = userService.selectUserList(new User());
    User u;
    if(null == users || users.isEmpty()) {
      u = new User();
    } else {
      u = users.get(0);
    }
    if(u.getType().equals("0")) {
      software.setSyncStatus("0");
    }
    return toAjax(softwareService.insertSoftware(software));
  }

  /** 修改软件 */
  @RequiresPermissions("lh:software:edit")
  @GetMapping("/edit/{id}")
  public String edit(@PathVariable("id") Long id, ModelMap mmap) {
    Software software = softwareService.selectSoftwareById(id);
    mmap.put("software", software);
    List<Project> list = projectService.selectProjectList(new Project());
    mmap.addAttribute("projectList", list);
    return prefix + "/edit";
  }

  /** 修改保存软件 */
  @RequiresPermissions("lh:software:edit")
  @Log(title = "软件", businessType = BusinessType.UPDATE)
  @PostMapping("/edit")
  @ResponseBody
  public AjaxResult editSave(Software software) {
    if(software!=null){
      if(software.getSupportHardwareVersion() == null){
        software.setSupportVersion("");
      }
      if(software.getSupportVersion() == null){
        software.setSupportVersion("");
      }
    }
    return toAjax(softwareService.updateSoftware(software));
  }

  /** 删除软件 */
  @RequiresPermissions("lh:software:remove")
  @Log(title = "软件", businessType = BusinessType.DELETE)
  @PostMapping("/remove")
  @ResponseBody
  public AjaxResult remove(String ids) {
    return toAjax(softwareService.deleteSoftwareByIds(ids));
  }

  @Log(title = "同步", businessType = BusinessType.UPDATE)
  @PostMapping("/sync")
  @ResponseBody
  public AjaxResult sync(String ids) {
    return toAjax(softwareService.sync(ids));
  }

  @Log(title = "同步", businessType = BusinessType.UPDATE)
  @PostMapping("/prodSync")
  @ResponseBody
  public AjaxResult prodSync(@RequestBody String requestStr) {
    return toAjax(softwareService.prodSync(requestStr));
  }

  @Log(title = "回退", businessType = BusinessType.UPDATE)
  @PostMapping("/back")
  @ResponseBody
  public AjaxResult back(String id) {
    return toAjax(softwareService.back(id));
  }

  @Log(title = "改变同步状态", businessType = BusinessType.UPDATE)
  @PostMapping("/changeStatus")
  @ResponseBody
  public AjaxResult changeStatus(@RequestBody Software s) {
    return toAjax(softwareService.updateSoftware(s));
  }


  /** 下载文件 */
  @RequestMapping("/download/{id}")
  public void download(@PathVariable("id") Long id, HttpServletResponse response) {
    Software software = softwareService.selectSoftwareById(id);
    String updateFile = software.getUpdateFile();

    try
    {
      if (!FileUtils.checkAllowDownload(updateFile))
      {
        throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", updateFile));
      }
      // 本地资源路径
      String localPath = RuoYiConfig.getProfile();
      // 数据库资源地址
      String downloadPath = localPath + StringUtils.substringAfter(updateFile, Constants.RESOURCE_PREFIX);
      // 下载名称
      String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
      response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
      FileUtils.setAttachmentResponseHeader(response, downloadName);
      FileUtils.writeBytes(downloadPath, response.getOutputStream());
    }
    catch (Exception e)
    {
      log.error("下载文件失败", e);
    }
    software.setDownloadNum(software.getDownloadNum() + 1);
    softwareService.updateSoftware(software);
  }

  @RequestMapping("/parent")
  public String parent(
      Model model,
      String type,
      String abledUpdateSoftware,
      String disabledSoftware,
      String checkedValues) {
    model.addAttribute("type", type);
    model.addAttribute("abledUpdateSoftware", abledUpdateSoftware);
    model.addAttribute("disabledSoftware", disabledSoftware);
    model.addAttribute("checkedValues", checkedValues);
    return prefix + "/parent";
  }

  @RequestMapping("/machineList")
  @ResponseBody
  public TableDataInfo machineList(
      String type, String abledUpdateSoftware, String disabledSoftware) {
    String excludeSN =
        StringUtils.isNotEmpty(type) && type.equals("able")
            ? disabledSoftware
            : abledUpdateSoftware;
    startPage();
    List<Machine> machineList = softwareService.selectMachineList(excludeSN);
    return getDataTable(machineList);
  }

  //  @RequestMapping("/download/{id}")
  //  public void download(@PathVariable("id") Long id, HttpServletResponse response) throws
  // IOException {
  //    OutputStream out = null;
  //    try {
  //      JSONArray jsonArray = new JSONArray();
  //      JSONObject jsonObject;
  //      for(int i=0;i<100;i++) {
  //        jsonObject = new JSONObject();
  //        jsonObject.put("time", "2023/6/7 0:00");
  //        jsonObject.put("value", "2.26");
  //        jsonArray.add(jsonObject);
  //      }
  //      // 创建一个pdf对象
  //
  //      ByteArrayOutputStream baos =
  //              PdfUtils.createPdf(
  //              "中化石化销售 (福建)有限公司光伏电站A\n逆变器日发电量(kwh)", "2023-06-07 00:00:00 - 2023-06-07 23:59:5",
  // new float[]{200, 200}, jsonArray);
  //      //设置请求返回类型
  //      response.setHeader("Content-Disposition", "attachment; filename=" + new String("中化石化销售
  // (福建)有限公司光伏电站A逆变器2023-06-07 00:00:00 - 2023-06-07 23:59:59发电量(kwh).pdf".getBytes(),
  // StandardCharsets.ISO_8859_1));
  //      response.setContentLength(baos.size());
  //      out = response.getOutputStream();
  //      baos.writeTo(out);
  //      out.flush();
  //    } catch (Exception e) {
  //      e.printStackTrace();
  //    } finally {
  //      out.close();
  //    }
  //
  //  }

}
